package filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 路径拦截
// 精确拦截 /user/ *  /*

/**
 * filter顺序
 * 1.web.xml 中注解
 * 2.排序，从上到下顺序
 */
@WebFilter(urlPatterns = "/user/*")
public class LoginFilter1 extends HttpFilter {

    @Override
    public void init() throws ServletException {
        // 只执行一次
        System.out.println("我是过滤器");
    }

    @Override
    public void destroy() {
        // 只执行一次
        System.out.println("我是过滤器，我将会被销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // 获取请求的路径
        String uri = req.getRequestURI();

        // 检查用户是否已经登录
        Object user = req.getSession().getAttribute("username");

        // 如果访问的是home.jsp且用户未登录，则重定向到登录页面
        if (uri.endsWith("user/home.jsp") && user == null) {
            res.sendRedirect(req.getContextPath() + "/home/login-2.jsp");
            return;
        }

        // 放行请求
        chain.doFilter(request, response);

        // 过滤器执行后的操作
        System.out.println("4");
    }
}
